package com.liry.security.config;

import com.alibaba.fastjson.JSON;
import com.liry.security.domain.vo.ResponseData;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

/**
 * 登录失败处理器
 * 序列化处理
 *
 * @author ALI
 * @since 2023/6/1
 */
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        AuthenticationException e) throws IOException, ServletException {
        // 处理失败的后置操作
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);

        ResponseData<Object> result = ResponseData.failed("用户名或密码错误");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(JSON.toJSONString(result));
        writer.flush();
    }
}
